import 'package:check_app/dao/addTask_dao.dart';
import 'package:check_app/dao/address_dao.dart';
import 'package:check_app/page/SelectPage.dart';
import 'package:check_app/util/pref_util.dart';
import 'package:check_app/util/uploadImage_util.dart';
import 'package:check_app/widgets/Picture.dart';
import 'package:check_app/widgets/deleteModal.dart';
import 'package:check_app/widgets/downModal.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'dart:convert' as convert;

class AddTaskPage extends StatefulWidget {
  final String code;
  final String contractNo;
  final int customerId;
  final String customerName;
  final int guideBookId;
  final String guideBookName;
  final String provinceName;
  final String provinceCode;
  final String cityName;
  final String cityCode;
  final String countyName;
  final String countyCode;
  const AddTaskPage({
    Key key,
    this.customerId,
    this.guideBookId,
    this.code,
    this.contractNo,
    this.customerName,
    this.guideBookName,
    this.provinceName,
    this.provinceCode,
    this.cityName,
    this.cityCode,
    this.countyName,
    this.countyCode,
  }) : super(key: key);
  @override
  State<StatefulWidget> createState() => new _AddTaskPageState();
}

class _AddTaskPageState extends State<AddTaskPage> {
  bool _loading = false;
  List<String> tabTitles;
  List<Map> nocheckGoodsList;
  TextEditingController _taskCode = new TextEditingController();
  TextEditingController _contractNo = new TextEditingController();
  TextEditingController _customerName = new TextEditingController();
  TextEditingController _bookName = new TextEditingController();
  TextEditingController _jianyanyuan = new TextEditingController();
  TextEditingController _address = new TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();
  int customerId;
  int bookId;
  List<String> proofUrlList = [];
  Map<String, String> provincesData;
  Map<String, dynamic> citiesData;
  String provinceCode;
  String provinceName;
  String cityCode;
  String cityName;
  String countyCode;
  String countyName;

  @override
  void initState() {
    super.initState();
    init();
    getAddress();
  }

  Future<Null> init() async {
    var currentName = await PrefUtil().getString('name');
    setState(() {
      _jianyanyuan.text = currentName;
    });
    if (widget.code != null) {
      setState(() {
        _taskCode.text = widget.code;
        _contractNo.text = widget.contractNo;
        customerId = widget.customerId;
        _customerName.text = widget.customerName;
        bookId = widget.guideBookId;
        _bookName.text = widget.guideBookName;
        provinceCode = widget.provinceCode;
        cityCode = widget.cityCode;
        countyCode = widget.countyCode;
        _address.text = widget.provinceName +
            '/' +
            widget.cityName +
            '/' +
            widget.countyName;
      });
    }
  }

  Future<Null> addTask() async {
    setState(() {
      _loading = true;
    });
    try {
      var result = await AddTaskDao.add({
        "code": _taskCode.text,
        "contractNo": _contractNo.text,
        "customerId": customerId,
        "guideBookId": bookId,
        "id": '',
        "proofUrlList": proofUrlList,
        "provinceCode": provinceCode,
        "provinceName": provinceName,
        "cityCode": cityCode,
        "cityName": cityName,
        "countyCode": countyCode,
        "countyName": countyName,
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
      Fluttertoast.showToast(
        msg: "网络错误",
      );
    }
    return null;
  }

  Future<Null> getAddress() async {
    setState(() {
      _loading = true;
    });
    try {
      var result = await AddressDao.fetchProvince();
      if (result['success']) {
        setState(() {
          provincesData = Map<String, String>.from(result['data']);
        });
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
      Fluttertoast.showToast(
        msg: "网络错误1",
      );
    }
    try {
      var result = await AddressDao.fetchCityArea();
      if (result['success']) {
        setState(() {
          citiesData = result['data'];
        });
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
      Fluttertoast.showToast(
        msg: "网络错误",
      );
    }
    setState(() {
      _loading = false;
    });
    return null;
  }

  Future<Null> selectAddress() async {
    Result result = await CityPickers.showCityPicker(
      context: context,
      height: 300,
      provincesData: provincesData,
      citiesData: citiesData,
      locationCode: countyCode,
    );
    if (result == null) return null;
    setState(() {
      _address.text =
          result.provinceName + '/' + result.cityName + '/' + result.areaName;
      provinceCode = result.provinceId;
      provinceName = result.provinceName;
      cityCode = result.cityId;
      cityName = result.cityName;
      countyCode = result.areaId;
      countyName = result.areaName;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(248, 248, 249, 1),
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text('添加任务'),
      ),
      body: SafeArea(
        child: ModalProgressHUD(
          inAsyncCall: _loading,
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 16),
                  padding: EdgeInsets.only(left: 16),
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    border: Border(
                      top: BorderSide(
                        width: 0.5,
                        color: Color.fromRGBO(229, 229, 229, 1),
                      ),
                    ),
                  ),
                  child: Form(
                    key: _formKey,
                    autovalidate: false,
                    child: Column(
                      children: <Widget>[
                        Container(
                          height: 62,
                          padding: EdgeInsets.only(right: 16),
                          width: double.infinity,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                width: 0.5,
                                color: Color.fromRGBO(229, 229, 229, 1),
                              ),
                            ),
                          ),
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: 120,
                                child: Text(
                                  '任务编码',
                                  style: TextStyle(
                                    fontSize: 16,
                                    height: 19 / 16,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: TextFormField(
                                  autofocus: false,
                                  controller: _taskCode,
                                  style: TextStyle(
                                    fontSize: 15.5,
                                    height: 22.5 / 15.5,
                                    color: Color.fromRGBO(43, 44, 46, 1),
                                  ),
                                  decoration: InputDecoration(
                                    fillColor: Colors.pink,
                                    contentPadding:
                                        EdgeInsets.fromLTRB(0, 0, 16, 0),
                                    hintText: "请输入任务编码",
                                    hintStyle: TextStyle(
                                      fontSize: 15.5,
                                      height: 22.5 / 15.5,
                                      color: Color.fromRGBO(181, 184, 189, 1),
                                    ),
                                    border: OutlineInputBorder(
                                      borderSide: BorderSide.none,
                                    ),
                                  ),
                                  validator: (v) {
                                    return v.trim().length > 0
                                        ? null
                                        : '任务编码不能为空';
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: 62,
                          padding: EdgeInsets.only(right: 16),
                          width: double.infinity,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                width: 0.5,
                                color: Color.fromRGBO(229, 229, 229, 1),
                              ),
                            ),
                          ),
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: 120,
                                child: Text(
                                  '合同编码',
                                  style: TextStyle(
                                    fontSize: 16,
                                    height: 19 / 16,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: TextFormField(
                                  autofocus: false,
                                  controller: _contractNo,
                                  style: TextStyle(
                                    fontSize: 15.5,
                                    height: 22.5 / 15.5,
                                    color: Color.fromRGBO(43, 44, 46, 1),
                                  ),
                                  decoration: InputDecoration(
                                    fillColor: Colors.pink,
                                    contentPadding:
                                        EdgeInsets.fromLTRB(0, 0, 16, 0),
                                    hintText: "请输入合同编码",
                                    hintStyle: TextStyle(
                                      fontSize: 15.5,
                                      height: 22.5 / 15.5,
                                      color: Color.fromRGBO(181, 184, 189, 1),
                                    ),
                                    border: OutlineInputBorder(
                                      borderSide: BorderSide.none,
                                    ),
                                  ),
                                  validator: (v) {
                                    return v.trim().length > 0
                                        ? null
                                        : '合同编码不能为空';
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: 62,
                          padding: EdgeInsets.only(right: 16),
                          width: double.infinity,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                width: 0.5,
                                color: Color.fromRGBO(229, 229, 229, 1),
                              ),
                            ),
                          ),
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () async {
                              var result = await Navigator.of(context)
                                  .push(MaterialPageRoute(builder: (_) {
                                return SelectPage(
                                  type: 'customer',
                                  title: '所属客户',
                                  placeholder: '请输入客户名称',
                                  label: '当前客户',
                                  value: _customerName.text,
                                );
                              }));
                              setState(() {
                                _customerName.text = result.name;
                                customerId = result.id;
                              });
                            },
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: 120,
                                  child: Text(
                                    '所属客户',
                                    style: TextStyle(
                                      fontSize: 16,
                                      height: 19 / 16,
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: TextFormField(
                                    enabled: false,
                                    controller: _customerName,
                                    style: TextStyle(
                                      fontSize: 15.5,
                                      height: 22.5 / 15.5,
                                      color: Color.fromRGBO(43, 44, 46, 1),
                                    ),
                                    decoration: InputDecoration(
                                      fillColor: Colors.pink,
                                      contentPadding:
                                          EdgeInsets.fromLTRB(0, 0, 16, 0),
                                      hintText: "请选择所属客户",
                                      hintStyle: TextStyle(
                                        fontSize: 15.5,
                                        height: 22.5 / 15.5,
                                        color: Color.fromRGBO(181, 184, 189, 1),
                                      ),
                                      border: OutlineInputBorder(
                                        borderSide: BorderSide.none,
                                      ),
                                    ),
                                    validator: (v) {
                                      return v.trim().length > 0
                                          ? null
                                          : '所属客户不能为空';
                                    },
                                  ),
                                ),
                                Image(
                                  image: AssetImage(
                                      'assets/images/chevron_gray.png'),
                                  width: 8,
                                  height: 13,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          height: 62,
                          padding: EdgeInsets.only(right: 16),
                          width: double.infinity,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                width: 0.5,
                                color: Color.fromRGBO(229, 229, 229, 1),
                              ),
                            ),
                          ),
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () async {
                              var result = await Navigator.of(context)
                                  .push(MaterialPageRoute(builder: (_) {
                                return SelectPage(
                                  type: 'book',
                                  title: '选择作业指导书',
                                  placeholder: '请输入作业指导书名称',
                                  label: '当前作业指导书',
                                  value: _bookName.text,
                                );
                              }));
                              setState(() {
                                _bookName.text = result.name;
                                bookId = result.id;
                              });
                            },
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: 120,
                                  child: Text(
                                    '作业指导书',
                                    style: TextStyle(
                                      fontSize: 16,
                                      height: 19 / 16,
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: TextFormField(
                                    enabled: false,
                                    controller: _bookName,
                                    style: TextStyle(
                                      fontSize: 15.5,
                                      height: 22.5 / 15.5,
                                      color: Color.fromRGBO(43, 44, 46, 1),
                                    ),
                                    decoration: InputDecoration(
                                      fillColor: Colors.pink,
                                      contentPadding:
                                          EdgeInsets.fromLTRB(0, 0, 16, 0),
                                      hintText: "请选择作业指导书",
                                      hintStyle: TextStyle(
                                        fontSize: 15.5,
                                        height: 22.5 / 15.5,
                                        color: Color.fromRGBO(181, 184, 189, 1),
                                      ),
                                      border: OutlineInputBorder(
                                        borderSide: BorderSide.none,
                                      ),
                                    ),
                                    validator: (v) {
                                      return v.trim().length > 0
                                          ? null
                                          : '作业指导书不能为空';
                                    },
                                  ),
                                ),
                                Image(
                                  image: AssetImage(
                                      'assets/images/chevron_gray.png'),
                                  width: 8,
                                  height: 13,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          height: 62,
                          padding: EdgeInsets.only(right: 16),
                          width: double.infinity,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                width: 0.5,
                                color: Color.fromRGBO(229, 229, 229, 1),
                              ),
                            ),
                          ),
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () async {
                              selectAddress();
                            },
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: 120,
                                  child: Text(
                                    '检测地点',
                                    style: TextStyle(
                                      fontSize: 16,
                                      height: 19 / 16,
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: TextFormField(
                                    enabled: false,
                                    controller: _address,
                                    style: TextStyle(
                                      fontSize: 15.5,
                                      height: 22.5 / 15.5,
                                      color: Color.fromRGBO(43, 44, 46, 1),
                                    ),
                                    decoration: InputDecoration(
                                      fillColor: Colors.pink,
                                      contentPadding:
                                          EdgeInsets.fromLTRB(0, 0, 16, 0),
                                      hintText: "请选择检测地点",
                                      hintStyle: TextStyle(
                                        fontSize: 15.5,
                                        height: 22.5 / 15.5,
                                        color: Color.fromRGBO(181, 184, 189, 1),
                                      ),
                                      border: OutlineInputBorder(
                                        borderSide: BorderSide.none,
                                      ),
                                    ),
                                    validator: (v) {
                                      return v.trim().length > 0
                                          ? null
                                          : '作业指导书不能为空';
                                    },
                                  ),
                                ),
                                Image(
                                  image: AssetImage(
                                      'assets/images/chevron_gray.png'),
                                  width: 8,
                                  height: 13,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          height: 62,
                          width: double.infinity,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                width: 0.5,
                                color: Color.fromRGBO(229, 229, 229, 1),
                              ),
                            ),
                          ),
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: 120,
                                child: Text(
                                  '检验员',
                                  style: TextStyle(
                                    fontSize: 16,
                                    height: 19 / 16,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: TextFormField(
                                  autofocus: false,
                                  enabled: false,
                                  controller: _jianyanyuan,
                                  style: TextStyle(
                                    fontSize: 15.5,
                                    height: 22.5 / 15.5,
                                    color: Color.fromRGBO(43, 44, 46, 1),
                                  ),
                                  decoration: InputDecoration(
                                    fillColor: Colors.pink,
                                    contentPadding:
                                        EdgeInsets.fromLTRB(0, 0, 16, 0),
                                    hintText: "请输入检验员",
                                    hintStyle: TextStyle(
                                      fontSize: 15.5,
                                      height: 22.5 / 15.5,
                                      color: Color.fromRGBO(181, 184, 189, 1),
                                    ),
                                    border: OutlineInputBorder(
                                      borderSide: BorderSide.none,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.fromLTRB(16, 12, 16, 8),
                  child: Text(
                    '原始凭证',
                    style: TextStyle(
                      fontSize: 14,
                      height: 20 / 14,
                      color: Color.fromRGBO(150, 151, 154, 1),
                    ),
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    border: Border(
                      top: BorderSide(
                        width: 0.5,
                        color: Color.fromRGBO(229, 229, 229, 1),
                      ),
                      bottom: BorderSide(
                        width: 0.5,
                        color: Color.fromRGBO(229, 229, 229, 1),
                      ),
                    ),
                  ),
                  child: Picture(
                    count: 4,
                    picList: proofUrlList,
                    onAdd: () {
                      showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return DownModal(
                            cameraCb: () async {
                              final url =
                                  await UploadImageUtil().getImageFromCamera();
                              setState(() {
                                proofUrlList.add(url);
                                _loading = false;
                              });
                            },
                            photoCb: () async {
                              final urlList = await UploadImageUtil()
                                  .loadAssets(9 - proofUrlList.length);
                              setState(() {
                                for (var value in urlList) {
                                  proofUrlList.add(value.toString());
                                }
                                _loading = false;
                              });
                            },
                          );
                        },
                      );
                    },
                    onRemove: (url) {
                      showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return DeleteModal(
                            onRemove: () {
                              setState(() {
                                proofUrlList.remove(url);
                              });
                            },
                          );
                        },
                      );
                    },
                  ),
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(16, 40, 16, 0),
                  width: double.infinity,
                  child: MaterialButton(
                    onPressed: () {
                      if ((_formKey.currentState as FormState).validate()) {
                        addTask();
                      }
                    },
                    color: Colors.blue,
                    textColor: Colors.white,
                    height: 44,
                    child: Text(
                      '提交',
                      style: TextStyle(
                        fontSize: 14,
                        height: 24 / 17,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
